package com.lty.mq.project;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Configuration
@Slf4j
public class RabbitMQConsumer {

    @Value("${spring.rabbitmq.host}")
    private String host;

    @Value("${rabbitmq.username:guest}")
    private String username;

    @Value("${rabbitmq.password:guest}")
    private String password;

    @Value("${rabbitmq.queue.name:hello}")
    private String queueName;

    @PostConstruct
    public void init() {
        new Thread(this::startConsuming).start();
    }

    private void startConsuming() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setUsername(username);
        factory.setPassword(password);

        try {
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();

            // 声明队列（确保队列存在）
            channel.queueDeclare(queueName, false, false, false, null);

            // 创建消费者
            com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                                           AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    log.info("Received Message: '{}'", message);
                }
            };
            // 开始消费
            channel.basicConsume(queueName, true, consumer);
        } catch (IOException | TimeoutException e) {
            log.error("Failed to start RabbitMQ consumer", e);
        }
    }
}